package com.oa.tools.jobs.impl;

import java.io.File;
import java.util.List;
import java.util.Map;

import com.oa.tools.TkMapper;
import com.oa.tools.entity.LbpmProcess;
import com.oa.tools.entity.OAFlowInstanceWithBLOBs;
import com.oa.tools.jobs.FlowHandlerTaskBase;
import com.oa.tools.utils.FileUtil;
import com.oa.tools.utils.MailUtil;
import com.oa.tools.utils.SysConfig;

import tk.mybatis.mapper.entity.Example;

public class FlowErrorMonitorTask extends FlowHandlerTaskBase{

	public FlowErrorMonitorTask(Map<String,TkMapper<?>> daoMap) {
		super(daoMap);
	}

	@Override
	public String exec(boolean notice, OAFlowInstanceWithBLOBs obj) throws Exception {
		return null;
	}

	@Override
	public String start(boolean notice,boolean force, long lastestDateMill) throws Exception {
		Example example = new Example(LbpmProcess.class);
		example.createCriteria().andEqualTo("fdStatus", FlowHandlerTaskBase.FLOW_STATUS_ERROR);
		List<LbpmProcess> objs = this.lbpmProcessDAO.selectByExample(example);
		
		StringBuilder result = new StringBuilder();
		for(LbpmProcess obj:objs) {
			OAFlowInstanceWithBLOBs flowObj = oAFlowInstanceDAO.selectByPrimaryKey(obj.getFdId());
			String recordPath = SysConfig.getRecordPath()+"/"+this.getClass().getName()+"_"+obj.getFdId()+".txt";
			if(new File(recordPath).exists()) {
				continue;
			}
			StringBuilder sb = new StringBuilder();
			sb.append("流程主题：");
			sb.append(flowObj.getDocSubject());
			sb.append("\r\n流程ID：");
			sb.append(obj.getFdId());
			sb.append("\r\n登录查看详情：");
			sb.append("<a href='http://oa.fengbangleasing.com/km/review/km_review_main/kmReviewMain.do?method=view&fdId="+obj.getFdId()+"' >"+flowObj.getDocSubject()+"</a>");
			sb.append("\r\n");
			
			FileUtil.writeTxt2File(sb.toString(), recordPath);
			result.append(sb);
		}
		
		if(result.length()>0) {
			String content = "<pre>Dear sushaolei \r\n"+result.toString()+"\r\n请尽快修改</pre>";
			String [] receiveMailAccounts = SysConfig.getSysSet("管理员接收邮箱").toArray(new String[0]);
			MailUtil.sendMail(receiveMailAccounts, "流程报错", content);
		}
		
		return result.toString();
	}

	
}
